package com.wz.datachannel.view;

import org.apache.log4j.Logger;

import com.wz.datachannel.util.log4j.Log4jManager;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

/**
 * 应用程序Activity的基类
 * 
 */
public class BaseActivity extends FragmentActivity {

	// 是否允许销毁
	public boolean allowDestroy = true;
	/**
	 * 允许窗口拖动
	 */
	private boolean mAllowWindowMove = false;
	/**
	 * 是否记录位置
	 */
	private boolean mIsSaveLoc = false;

	protected static Logger mLog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 添加Activity到堆栈
		mLog = Log4jManager.getInstance();
	}

	protected void setAllowWindowMove(boolean isAllowMove, boolean isSaveLoc) {
		this.mAllowWindowMove = isAllowMove;
		this.mIsSaveLoc = isSaveLoc;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private float mTouchStartX = -1;
	private float mTouchStartY = -1;
	private float x;
	private float y;

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		//获取相对屏幕的坐标，即以屏幕左上角为原点
		if (mAllowWindowMove) {
			x = event.getRawX();
			y = event.getRawY();
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				//获取相对View的坐标，即以此View左上角为原点  
				mTouchStartX = event.getX();
				mTouchStartY = event.getY();
				break;
			case MotionEvent.ACTION_MOVE:
				updateViewPosition();
				break;
			case MotionEvent.ACTION_UP:
				updateViewPosition();
				saveViewPosition();
				mTouchStartX = mTouchStartY = -1;
				break;
			case MotionEvent.ACTION_OUTSIDE:
				//saveViewPosition();
				break;
			}
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 更新位置
	 * @author wei
	 */
	private void updateViewPosition() {
		if (mTouchStartX < 0 || mTouchStartY < 0) {
			return;
		}
		//更新浮动窗口位置参数  
		int newX = (int) (x - mTouchStartX);
		int newY = (int) (y - mTouchStartY);
		Window window = getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		window.setGravity(Gravity.LEFT | Gravity.TOP);
		lp.x = newX;// 新位置X坐标
		lp.y = newY; // 新位置Y坐标 
		window.setAttributes(lp);
	}

	/**
	 * 存储位置
	 * @author wei
	 */
	private void saveViewPosition() {
		if (mIsSaveLoc) {
			//
		}
	}
}
